#include "accountmodel.h"

#include "cashplusplus.h"

AccountModel::AccountModel(QObject* parent)
	: QSqlRelationalTableModel(parent, QSqlDatabase::database(CashPlusPlus::DB_NAME))
{
	setTable("accounts");

	setEditStrategy(OnRowChange);
	setSort(1, Qt::AscendingOrder);

	setRelation(2, QSqlRelation("account_types", "id", "name"));

	setHeaderData(0, Qt::Horizontal, tr("ID"));
	setHeaderData(1, Qt::Horizontal, tr("Name"));
	setHeaderData(2, Qt::Horizontal, tr("Type"));
	setHeaderData(3, Qt::Horizontal, tr("Balance"));

	select();
}

void AccountModel::addAccount()
{
	submitAll();

	QSqlQuery q(database());

	q.prepare("INSERT INTO accounts VALUES (NULL, ?, ?, ?)");
	q.addBindValue("<New Account>");
	q.addBindValue(CashPlusPlus::CASH);
	q.addBindValue(0.0);
	q.exec();
	q.finish();

	select();
}

void AccountModel::deleteAccounts(const QModelIndexList& currentSelection)
{
	submitAll();
	setEditStrategy(OnManualSubmit);

	for (int i = 0; i < currentSelection.count(); ++i)
	{
		if (currentSelection.at(i).column() != 0)
		{
			continue;
		}

		int id = currentSelection.at(i).model()->index(currentSelection.at(i).row(), 0).data().toInt();

		QSqlQuery q(database());

		q.prepare("DELETE FROM transactions WHERE account_id = ?");
		q.addBindValue(id);
		q.exec();
		q.exec("VACUUM");

		removeRow(currentSelection.at(i).row());
	}

	submitAll();
	setEditStrategy(OnRowChange);
}

QPair<int,int> AccountModel::ndAccounts()
{
	int domerAccount = -1;
	int flexAccount = -1;

	QSqlQuery q(database());
	q.exec("SELECT id, type FROM accounts");
	while(q.next())
	{
		int type = q.value(1).toInt();

		if (CashPlusPlus::DOMER == type)
		{
			domerAccount = q.value(0).toInt();
		}
		else if (CashPlusPlus::FLEX == type)
		{
			flexAccount = q.value(0).toInt();
		}
	}

	return QPair<int,int>(domerAccount,flexAccount);
}

void AccountModel::updateNDBalances(double domer, double flex)
{
	QPair<int,int> accounts = ndAccounts();
	int domer_id = accounts.first;
	int flex_id = accounts.second;

	QSqlQuery q(database());
	q.prepare("UPDATE accounts SET amount = ? WHERE id = ?");

	if (domer_id > -1)
	{
		q.addBindValue(domer);
		q.addBindValue(domer_id);
		q.exec();
	}

	if (flex_id > -1)
	{
		q.addBindValue(flex);
		q.addBindValue(flex_id);
		q.exec();
	}

	select();
}
